// 弹窗复选
import React, { useState, useMemo, useEffect } from 'react';
import { Modal, Button, Input, Checkbox, Tree } from 'antd';
import _ from 'lodash';
//@ts-ignore
import { CloseOutlined, SearchOutlined } from '#/utils/antdIcons';
import type { DataNode } from 'antd/es/tree';
import TRNotification from '#/utils/notification.js';
import planIcon from '@/assets/img/plan_icon.png';
import styles from './index.less';

interface IProps {
  threeSelectData?: DataNode[];
  value?: React.Key[];
  leftNodes?: any[];
  onPress: (data: Record<string, any>) => void;
  onOk?: (params?: any) => void;
}

const ModalComponent = (props: IProps) => {
  const { threeSelectData = [], value: _val, leftNodes: _leftNodes, onPress, onOk } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [checkAll, setCheckAll] = useState<boolean>(false);
  const [indeterminate, setIndeterminate] = useState<boolean>(false);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [checkedNodes, setCheckedNodes] = useState<any>([]);
  const [leftNodes, setLeftNodes] = useState<any[]>([]);

  useEffect(() => {
    setLeftNodes(_leftNodes || []);
  }, [threeSelectData]);

  useEffect(() => {
    if (_val) {
      setCheckedKeys(_val);
      const _checkedNodes: any[] = [];
      _val.forEach((item) => {
        const obj = _leftNodes?.find((a) => a?.key === item);
        if (obj) {
          _checkedNodes.push(obj);
        }
      });
      setCheckedNodes(_checkedNodes);
      setCheckAll(_val?.length === _leftNodes?.length);
      setIndeterminate(_val?.length > 0 && _val?.length !== _leftNodes?.length);
    }
  }, [_val]);

  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    let newExpandedKeys: any[] = [];
    if (value) {
      newExpandedKeys = leftNodes
        .map((item: any) => {
          if (item?.title?.indexOf(value) > -1) {
            return item?.parentKey || item?.key;
          } else {
            return null;
          }
        })
        .filter((item) => {
          return !!item;
        });
    }
    setExpandedKeys(newExpandedKeys as React.Key[]);
    setSearchValue(value);
    setAutoExpandParent(true);
  };

  const onCheck = (checkedKeysValue: React.Key[]) => {
    const _checkedKeys: string[] = [];
    checkedKeysValue.forEach((item) => {
      const obj = leftNodes?.find((a) => a?.key === item);
      if (obj) {
        _checkedKeys.push(obj?.key);
      }
    });
    const _checkedNodes = _checkedKeys.map((a) => {
      return leftNodes.find((item) => a === item?.key);
    });
    setCheckedNodes(_checkedNodes);
    setCheckedKeys(_checkedKeys);
    setCheckAll(_checkedKeys?.length === _leftNodes?.length);
    setIndeterminate(_checkedKeys?.length > 0 && _checkedKeys?.length !== _leftNodes?.length);
  };

  const onSelectAll = (e: any) => {
    const _checkAll = e.target.checked;
    const _checkedNodes = _checkAll ? [...leftNodes] : [];
    const _checkedKeys = _checkedNodes.map((x: any) => x.key);
    setCheckAll(_checkAll);
    setIndeterminate(false);
    setCheckedKeys(_checkedKeys);
    setCheckedNodes(_checkedNodes);
  };

  const treeData = useMemo(() => {
    const loop = (data: DataNode[]): DataNode[] =>
      data.map((item) => {
        const strTitle = (item?.title || '') as string;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span className={styles.search_act}>{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{strTitle}</span>
          );
        if (item.children) {
          return { title, key: item.key, children: loop(item.children) };
        }

        return {
          title,
          key: item.key,
        };
      });

    return loop(threeSelectData);
  }, [searchValue]);

  // 清空
  const onClearAll = () => {
    setCheckAll(false);
    setIndeterminate(false);
    setCheckedKeys([]);
    setCheckedNodes([]);
    setExpandedKeys([]);
  };

  // 删除已选项
  const onRemove = (i: number) => {
    const _checkedNodes = _.cloneDeep(checkedNodes);
    _checkedNodes.splice(i, 1);
    const _checkedKeys = _checkedNodes.map((x: any) => x.key);
    const _checkAll = !!checkedKeys.length && checkedKeys.length === leftNodes.length;
    setCheckAll(_checkAll);
    setCheckedNodes(_checkedNodes);
    setIndeterminate(_checkedKeys.length ? true : false);
    setCheckedKeys(_checkedKeys);
  };

  // 取消按钮
  const _onCancel = async () => {
    setVisible(false);
    onPress({ index: 0, checkedKeys, checkedNodes });
  };

  // 确认
  const _onOk = () => {
    let _checkedKeys: React.Key[] = [];
    let _checkedNodes: DataNode[] = [];
    if (checkedNodes.length === 0) {
      _checkedKeys = _val || [];
      _val?.forEach((item) => {
        const obj = leftNodes?.find((a) => a?.key === item);
        if (obj) {
          _checkedNodes.push(obj);
        }
      });
    } else {
      _checkedKeys = checkedNodes.map((x: any) => x.key);
      _checkedNodes = _.cloneDeep(checkedNodes);
    }
    onOk && onOk(_checkedKeys);
    setVisible(false);
    onPress({
      index: 1,
      checkedKeys: _checkedKeys,
      checkedNodes: _checkedNodes,
    });
  };

  const footerRender = () => {
    return [
      <Button key="dtest1" onClick={_onCancel}>
        取消
      </Button>,
      <Button key="dtest2" type="primary" onClick={_onOk}>
        确定
      </Button>,
    ];
  };

  return (
    <Modal
      className={styles.modal}
      centered
      width={672}
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>资料</span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <div className={styles.treebox}>
          <div className={styles.box_header}>
            <Input
              placeholder="搜索"
              suffix={<SearchOutlined />}
              allowClear={true}
              onChange={onChange}
            />
          </div>
          <div className={styles.box_content}>
            <div className={styles.checkBox}>
              <Checkbox checked={checkAll} indeterminate={indeterminate} onChange={onSelectAll}>
                全选
              </Checkbox>
            </div>
            <div className={styles.tree}>
              <Tree
                onExpand={onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                // @ts-ignore
                onCheck={onCheck}
                checkedKeys={checkedKeys}
                treeData={treeData}
                checkable
                height={250}
              />
            </div>
          </div>
        </div>

        <div className={styles.choosebox}>
          <div className={styles.box_header}>
            <div>{`已选${checkedKeys.length}项`}</div>
            <div className={styles.clear} onClick={onClearAll}>
              清空
            </div>
          </div>
          <div className={styles.box_content}>
            <ul className={styles.chooseList}>
              {checkedNodes.map((item: any, index: number) => {
                return (
                  <li key={item.key}>
                    <div className={styles.chooseName}>{item.title}</div>
                    <CloseOutlined className={styles.close} onClick={() => onRemove(index)} />
                  </li>
                );
              })}
            </ul>
          </div>
        </div>
      </div>
    </Modal>
  );
};

class CheckboxModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new CheckboxModal();
